package com.jp.knowledge.dialog;

import android.app.Activity;
import android.content.Context;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.JsonObject;
import com.jp.knowledge.R;
import com.jp.knowledge.adapter.JPBaseAdpter;
import com.jp.knowledge.adapter.JPViewHolder;
import com.jp.knowledge.db.DBHelper;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.util.ResultSubscriber;

import java.util.List;

/**
 * Created by jiayen on 16/11/15.
 *
 * 搜索popuWindow
 */

public class SearchPopuWindow extends PopupWindow implements ResultSubscriber.OnResultListener {

    private ListView listView;

    private List<String> keys;

    private TextAdapter adapter;
    private OnSearchItemListener lisertern;

    private View conentView;
    private Context mContext;

    public void setOnItemLisertern(OnSearchItemListener lisertern) {
        this.lisertern = lisertern;
    }


    public SearchPopuWindow(Activity context) {
        super(context);
        this.mContext=context;
//        context.getWindow().setBackgroundDrawable(context.getResources().getDrawable(R.color.hafl_translate));

        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        conentView = inflater.inflate(getLayoutId(), null);
        int h = context.getWindowManager().getDefaultDisplay().getHeight();
        int w = context.getWindowManager().getDefaultDisplay().getWidth();
        // 设置SelectPicPopupWindow的View
        this.setContentView(conentView);
        // 设置SelectPicPopupWindow弹出窗体的宽
        DisplayMetrics d = context.getResources().getDisplayMetrics(); // 获取屏幕宽、高用
        int width = (int) (d.widthPixels*1.0);
        this.setWidth(width);
        // 设置SelectPicPopupWindow弹出窗体的高
        this.setHeight(RelativeLayout.LayoutParams.WRAP_CONTENT);
        // 设置SelectPicPopupWindow弹出窗体可点击
//        this.setFocusable(true);
//        this.setOutsideTouchable(true);
        // 刷新状态
        this.update();
        // 实例化一个ColorDrawable颜色为半透明
        ColorDrawable dw = new ColorDrawable(0x90000000);
        // 点back键和其他地方使其消失,设置了这个才能触发OnDismisslistener ，设置其他控件变化等操作
        this.setBackgroundDrawable(dw);
//        this.setAnimationStyle(android.R.style.Animation_Dialog);

        Window window = context.getWindow();
        WindowManager.LayoutParams layoutParams = window.getAttributes();
        window.setBackgroundDrawableResource(R.color.hafl_translate); //设置对话框背景为透明
//        layoutParams.alpha = 0.8f;
        layoutParams.width= WindowManager.LayoutParams.MATCH_PARENT;
        layoutParams.height= WindowManager.LayoutParams.MATCH_PARENT;
        window.setAttributes(layoutParams);
        initView();
    }

    public int getLayoutId() {
        return R.layout.search_popuwindow_layout;
    }

    public boolean isEmpty(){
        if(keys == null || keys.size() == 0)
            return true;
        else
            return false;
    }

    /**
     * 初始化数据
     */
    public void initView() {
//        this.setFocusable(true);
//        this.setAnimationStyle(R.style.search_window);
        this.setOutsideTouchable(false);//点击空白处不消失
//        设置弹出窗体需要软键盘，
        this.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
//        再设置模式，和Activity的一样，覆盖，调整大小。
        this.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);

        listView = (ListView) conentView.findViewById(R.id.listView);

//        List<SearchKey> searchKeys = new ArrayList<>();
//        for (int i = 0; i <10 ; i++) {
//            SearchKey key = new SearchKey();
//            key.setName("test_"+i);
//            searchKeys.add(key);
//        }
        adapter = new TextAdapter(mContext,keys);
        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                SearchPopuWindow.this.dismiss();
                if(lisertern!=null)
                    lisertern.onItemListener(keys.get(position));
            }
        });
    }

    /**
     * 搜索关键字
     */
    public void searchKeyWord(String key){
        JsonObject param = new JsonObject();
        param.addProperty("keyword",key);
        HttpHelper.getInstance(mContext).jpSearch(param,1,this);
    }

    @Override
    public void onStart(int requestType) {

    }

    @Override
    public void onCompleted(int requestType) {

    }

    @Override
    public void onError(int requestType) {

    }

    @Override
    public void onNext(IModel data, int requestType) {
        if(data.getErrcode()==0){
            List<String>  temp = (List<String>) data.getData();
            if(temp!=null&&temp.size()>0)keys=temp;
            adapter.updataAdapter(keys);
            if(this.searchRemindCallback != null)
                this.searchRemindCallback.showRemindPopWindow();
        }
    }


    /**
     * 适配器
     */
    private class  TextAdapter extends JPBaseAdpter<String> implements View.OnClickListener {

        public TextAdapter(Context context, List infos) {
            super(context, infos);
        }

        @Override
        protected int getLayoutId(int position) {
            return R.layout.search_item;
        }

        @Override
        protected void renderData(JPViewHolder holder, String item, int position) {
            ImageView delIcon = holder.getView(R.id.del_icon);
            TextView name = holder.getView(R.id.name);
            name.setText(item);
            delIcon.setTag(position);
            delIcon.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            int postion = (int) v.getTag();
            //删除数据库中的记录
            DBHelper.getInstance().delete(getItem(postion));
            removeItem(postion);
        }
    }

    public void clearList(){
        if(keys != null)
            keys.clear();
        adapter.updataAdapter(keys);
    }

    public interface  OnSearchItemListener{
        void onItemListener(String key);
    }

    private SearchRemindCallback searchRemindCallback;
    public void setSearchRemindCallback(SearchRemindCallback searchRemindCallback){
        this.searchRemindCallback = searchRemindCallback;
    }
    /* 通知搜索界面展示预搜索结果 */
    public interface SearchRemindCallback{
        void showRemindPopWindow();
    }


    @Override
    public void showAsDropDown(View anchor) {
        if (Build.VERSION.SDK_INT < 24) {
            showAsDropDown(anchor, 0, 0);
        } else {
            int[] location = new int[2];
            // 获取控件在屏幕的位置
            anchor.getLocationOnScreen(location);
            showAtLocation(anchor, Gravity.NO_GRAVITY, 0, location[1] + anchor.getHeight());
        }
    }
}
